package com.atguigu.spzx.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.ValidateCodeVo;
import com.atguigu.spzx.tools.SpzxConsts;
import jakarta.annotation.Resource;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author LT
 * @create 2024-03-28-10:11
 */
@Component
public class SpzxGlobalAuthFilter implements GlobalFilter {

    AntPathMatcher matcher = new AntPathMatcher();
    @Resource
    RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        boolean match = matcher.match("/api/**/auth/**", path);
        if (!match){
            return chain.filter(exchange);
        }

        //需要鉴权的路径
        String token = request.getHeaders().getFirst("token");
        Boolean isLogin = false;
        if (!StringUtils.isEmpty(token)){
            isLogin = redisTemplate.hasKey(SpzxConsts.SPZX_USER_LOGIN_PREFIX + token);
        }
        if (isLogin){
            //表示已登录，放行
            return chain.filter(exchange);
        }

        //访问的路径需要鉴权，但是没有token或者token失效，拒绝请求，响应一个Result对象。
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", ResultCodeEnum.LOGIN_STATUS_ERROR.getCode());
        jsonObject.put("message",ResultCodeEnum.LOGIN_STATUS_ERROR.getMessage());
        String rJson = jsonObject.toJSONString();
        Mono<DataBuffer> mono = Mono.just(response.bufferFactory().wrap(rJson.getBytes()));

        return response.writeWith(mono);
    }
}
